
import React, { useState, useEffect } from 'react'
import { Table, Pagination, Button, Input, Space, Modal, Form, message, DatePicker } from 'antd';
import axios from 'axios';


export default function Parts() {
  const [dataSource, setDataSource] = useState([])
  const [dataTotal, setDataTotal] = useState([])
  const [dataCompany, setDataCompany] = useState("")
  const [dataName, setDataName] = useState("")
  const [selectData, setSelectData] = useState([])
  const [messageApi, contextHolder] = message.useMessage();
  const [open, setOpen] = useState(false);
  const [proTime, setProTime] = useState("");
  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {

      setSelectData(selectedRows)
    },
    getCheckboxProps: (record) => ({
      disabled: record.name === 'Disabled User',
      // Column configuration not to be checked
      name: record.name,
    }),
  };
  useEffect(() => {
    axios.get("/partstore/selectpart").then(res => {
      setDataSource(res.data)
      setDataTotal(res.data.length)
    })
  }, [])

  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      align: "center",
      fixed: "left",
      width: "5%",
      render: (text, record, index) => {
        return <span style={{ fontSize: "12px" }}>{index + 1}</span>
      }
    },
    {
      title: 'id',
      dataIndex: 'id',
      key: 'id',
      align: "center",
      fixed: "left",
      width: "5%",
      hidden: true,
      render: (text, record, index) => {
        return <span style={{ fontSize: "12px" }}>{text}</span>
      }
    },
    {
      title: '零件名称',
      dataIndex: 'partname',
      key: 'partName',
      align: "center",
      width: '15%',
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{text}</span>
      }
    },
    {
      title: "生产公司",
      dataIndex: 'procompany',
      key: 'proCompany',
      align: "center",
      className: "wrapTitle",
      width: '20%',
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{text}</span>
      }
    },
    {
      title: '生产日期',
      dataIndex: 'protime',
      key: 'proTime',
      align: "center",
      className: "wrapTitle",
      width: '15%',
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{text}</span>
      }
    },
    {
      title: '备注',
      dataIndex: 'comment',
      key: 'comment',
      align: "left",
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{text}</span>
      }
    }
  ];
  const [selectionType, setSelectionType] = useState('checkbox');
  const selectSome = () => {
    axios.post("/partstore/selectsomepart", {
      "partname": dataName,
      "procompany": dataCompany
    }).then(res => {
      setDataSource(res.data)
      setDataTotal(res.data.length)
    })
  }
  const inputUpdate = (e, num) => {
    if (num === 1) {
      setDataCompany(e.currentTarget.value)
    } else {
      setDataName(e.currentTarget.value)
    }
  }
  const buySome = () => {
    if (selectData.length != 0) {
      axios.post("/part/insertpart", selectData).then(res => {
        messageApi.info("购进成功!")
      })

    } else {
      messageApi.info("请选择零件!")
    }
  }
  const insertPart = () => {
    setOpen(true);
  }
  const onChange = (date, dateString) => {
    setProTime(dateString)
  };
  const onCreate = (values) => {
    axios.post("/partstore/insertpartstore", { "partname": values.partname, "procompany": values.procompany, "protime": proTime, "comment": values.comment }).then(res => {
      if (res.data) {
        window.location.reload();
        messageApi.info("添加成功!")
      } else {
        messageApi.info("添加失败!")
      }

    })
    setOpen(false);
  };
  const CollectionCreateForm = ({ open, onCreate, onCancel }) => {
    const [form] = Form.useForm();

    return (
      <Modal
        open={open}
        title="添加零件"
        okText="确定"
        cancelText="取消"
        onCancel={onCancel}
        onOk={() => {
          form
            .validateFields()
            .then((values) => {
              form.resetFields();
              onCreate(values);
            })
            .catch((info) => {
              console.log('Validate Failed:', info);
            });
        }}
      >
        <Form
          form={form}
          layout="vertical"
          name="form_in_modal"
          initialValues={{
            modifier: 'public',
          }}
        >
          <Form.Item
            name="partname"
            label="零件名称"
            rules={[
              {
                required: true,
                message: '未输入零件名称！',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="procompany"
            label="生产公司"
            rules={[
              {
                required: true,
                message: '未输入生产公司！',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="protime"
            label="生产日期"
            rules={[
              {
                required: true,
                message: '未输入生产日期！',
              },
            ]}
          >
            <DatePicker onChange={onChange} placeholder='请选择日期' style={{ width: "100%" }} />

          </Form.Item>
          <Form.Item
            name="comment"
            label="备注"
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    );
  };
  return (
    <div>
      {contextHolder}
      <Space
        direction="vertical"
        size="middle"
        style={{
          display: 'flex',
        }}>
        <div>
          <div style={{ float: "left" }}>
            <Input placeholder="请输入公司名称" style={{ width: "200px" }} onBlur={(e) => { inputUpdate(e, 1) }} />
            <Input placeholder="请输入零件名称" style={{ width: "200px", margin: "0 0 0 10px" }} onBlur={(e) => { inputUpdate(e, 2) }} />
            <Button type='primary' style={{ color: "white", fontSize: "12px", borderRadius: "4px", margin: "0 0 0 10px" }} onClick={() => { selectSome() }}>查询</Button>
          </div>
          <div style={{ float: "right" }}>
            <Button style={{ color: "black", fontSize: "12px", borderRadius: "4px", margin: "0 0 0 10px" }} onClick={() => { insertPart() }}>添加</Button>
            <Button style={{ color: "black", fontSize: "12px", borderRadius: "4px", margin: "0 0 0 10px" }} onClick={() => { buySome() }}>购进</Button>
          </div>
        </div>
      </Space>
      <Table
        rowSelection={{
          type: selectionType,
          ...rowSelection,
        }}
        rowKey={(item) => item.id}
        columns={columns} dataSource={dataSource} style={{ margin: "5px 0 0 0" }}
        pagination={{ pageSize: 10 }}
        size='small'
        scroll={{ x: 1200 }}
      >
      </Table>

      <CollectionCreateForm
        open={open}
        onCreate={onCreate}

        onCancel={() => {
          setOpen(false);
        }}
      />
    </div >
  )
}
